//
//  QRCodeTool.m
//  TenMinDemo
//
//  Created by Shawn Li on 2021/3/14.
//  Copyright © 2021 CYXiang. All rights reserved.
//

#import "QRCodeTool.h"
#import <CoreImage/CoreImage.h>

@implementation QRCodeTool
+ (UIImage *)getQRCodeImg:(NSString *)info{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    //把信息转化为NSData
    NSData *infoData = [info dataUsingEncoding:NSUTF8StringEncoding];
    //滤镜对象kvc存值
    [filter setValue:infoData forKeyPath:@"inputMessage"];

    //我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
//     NSLog(@"%@",qrImageFilter.inputKeys);
     /*
        inputMessage,        //二维码输入信息
        inputCorrectionLevel //二维码错误的等级,就是容错率
      */
    
    CIImage *outImage = [filter outputImage];
    return  [self createNonInterpolatedUIImageFormCIImage:outImage withSize:300];

}

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
  CGRect extent = CGRectIntegral(image.extent);
  CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));

  //1.创建bitmap;
  size_t width = CGRectGetWidth(extent) * scale;
  size_t height = CGRectGetHeight(extent) * scale;
  CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
  CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
  CIContext *context = [CIContext contextWithOptions:nil];
  CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
  CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
  CGContextScaleCTM(bitmapRef, scale, scale);
  CGContextDrawImage(bitmapRef, extent, bitmapImage);

  //2.保存bitmap到图片
  CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
  CGContextRelease(bitmapRef);
  CGImageRelease(bitmapImage);
  return [UIImage imageWithCGImage:scaledImage];
}
@end
